<?php
// +----------------------------------------------------------------------
// |MCPHP[基于ThinkPHP6.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://www.mingchangruanjian.com
// +----------------------------------------------------------------------
// | Author jokerfei [ jokerfei377@gmail.com ]
// +----------------------------------------------------------------------
// | 铭畅软件 技术部 出品
// +----------------------------------------------------------------------
namespace addons\WeChat\controller;


/**
 * 设置配置参数
 * @author jokerfei<215628355@qq.com>
 */
class Base {

    public $config;

    /**
     * 自动写入配置缓存
     */
    public function __construct() {
        
        $this->config = addons_config('Wechat');
        if($this->config["sslcert_path"]){            
            $this->config["sslcert_path"] = $this->writeSslFile($this->config["sslcert_path"],"apiclient_cert");
        }        
        if($this->config["sslkey_path"]){       
            $this->config["sslkey_path"] = $this->writeSslFile($this->config["sslkey_path"],"apiclient_key");
        }
    }
    
    //写入证书文件
    private function writeSslFile($sslContent ,$fileName = null){    
        $md5Content = md5($sslContent);        
        if(!$fileName){
            $fileName =  $md5Content;    
        }         
        $path =  __DIR__ . '/../sdk/cert/'.$fileName.'.pem';
        if(!file_exists($path) || $md5Content !== md5_file($path)){
            $w = file_put_contents($path, $sslContent);
            if(!$w){
                throw new \Exception("SAVE SSL FILE ERROR");
            }
        }          
        return $path;
    }

    //打开连接
    public function curl($url, $post = false, $toJson = true, $query = null, $headers = null) {
        if (is_array($post) && $toJson) {
            $post = json_encode($post, JSON_UNESCAPED_UNICODE);
        }

        if ($query) {
            $url = $url.'?'.http_build_query($query);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if ($headers) {
            curl_setopt($ch, CURLOPT_HEADER, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //这个是重点。

        if ($post) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        $result = curl_exec($ch);
        
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        list($header, $body) = explode("\r\n\r\n", $result, 2);
        curl_close($ch);

        return $body;
    }
}
